package com.tgpms.web.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.util.PageView;
import com.tgpms.web.system.entity.SmDatasource;
import com.tgpms.web.system.service.SmDatasourceService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author May
 *
 * 查询语句配置表相关接口
 */
@Api(value = "smDatasource", tags = "查询语句配置表相关接口")
@RestController
@RequestMapping("/quality/system/smDatasource")
public class SmDatasourceController {

    @Autowired
    private SmDatasourceService smDatasourceService;

    @Resource
    private VformInterface vformInterface;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询所有的配置表信息
     */
    @ApiOperation(value = "查数据源相关信息", notes = "查数据源相关信息", httpMethod = "POST")
    @PostMapping("/queryAll")
    public PageView queryAll(@RequestParam(value = "dsCode", required = false) String dsCode,
                             @RequestParam(value = "tblName", required = false) String tblName,
                             @RequestParam(value = "dsDesc", required = false) String dsDesc,
                             @RequestParam(value = "orderClause", required = false) String orderClause,
                             @RequestParam("pageNo") Integer pageNo) {
        PageView pageView = new PageView();
        Map<String, String> map = new HashMap<>();
        map.put("dsCode", dsCode);
        map.put("tblName", tblName);
        map.put("dsDesc", dsDesc);
        map.put("orderClause", orderClause);
        pageView.setPageNow(pageNo);
        pageView.setQueryMap(map);
        try {
            pageView = smDatasourceService.queryAll(pageView);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return pageView;
    }

    /**
     * 查询单条配置表信息
     *
     * @param dsCode
     * @return null
     */
    @ApiOperation(value = "查询单条配置表信息", notes = "查询单条配置表信息", httpMethod = "POST")
    @PostMapping(value = "/findByDsCode")
    public Result findByDsCode(@RequestParam("dsCode") String dsCode) {
        Result result = new Result();
        SmDatasource byDsCode = new SmDatasource();
        try {
            byDsCode = smDatasourceService.findByDsCode(dsCode);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(ExceptionExplain.ERROR_BY_QUERY.getExplain());
            result.setSuccess(false);
        }
        result.setData(byDsCode);
        return result;
    }

    /**
     * 插入/更新配置表信息
     *
     * @param smDatasource
     * @return null
     */
    @ApiOperation(value = "插入/更新配置表信息", notes = "插入/更新配置表信息", httpMethod = "POST")
    @PostMapping(value = "/changeDatasource")
    public Result changeDatasource(@RequestBody SmDatasource smDatasource) {
        Result result = new Result();
        Integer status = 1;
        try {
             status = smDatasourceService.changeSmDatasource(smDatasource);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (status == 1) {
            result.setData(true);
        } else if (status == -1) {
            result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
            result.setSuccess(false);
        } else if (status == -2) {
            result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
            result.setSuccess(false);
        } else {
            result.setMsg(ExceptionExplain.ERROR_BY_INFOS.getExplain());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 删除配置表信息
     *
     * @param dsCode
     * @return null
     */
    @ApiOperation(value = "删除配置表信息", notes = "删除配置表信息", httpMethod = "DELETE")
    @DeleteMapping(value = "/delDatasource")
    public Result delDatasource(@RequestParam("dsCode") String dsCode) {
        Result result = new Result();
        Integer status = 1;
        try {
            status = smDatasourceService.delSmDatasource(dsCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (status == 1) {
            result.setData(true);
        } else {
            result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 动态执行 SQL
     *
     * @param params
     * @return null
     */
    @ApiOperation(value = "动态执行SQL", notes = "动态执行SQL", httpMethod = "POST")
    @PostMapping(value = "/executionSql")
    public Result executinoSql(@RequestParam Map<String, String> params) {
        Result result = new Result();
        SmDatasource byDsCode = smDatasourceService.findByDsCode(params.get("dsCode"));
        if (null == byDsCode) {
            result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
            result.setSuccess(false);
            return result;
        }
        params.put("sql", byDsCode.getSelectClause());
        List<Map<String, String>> maps = smDatasourceService.executionSql(params);
        result.setData(maps);
        return result;
    }

    /**
     * 动态执行 SQL 并分页
     *
     * @param params
     * @return null
     */
    @ApiOperation(value = "动态执行SQL - 分页处理", notes = "动态执行SQL - 分页处理", httpMethod = "POST")
    @PostMapping(value = "/executinoSqlWithPage")
    public PageView executinoSqlWithPage(@RequestParam Map<String, String> params) {
        PageView pageView = new PageView();
        Integer pageNow = Integer.parseInt(params.get("pageNow"));
        Integer pageSize = Integer.parseInt(params.get("pageSize"));
        String dsCode = params.get("dsCode");
        params.remove("pageNow");
        params.remove("pageSize");
        params.remove("dsCode");
        SmDatasource byDsCode = smDatasourceService.findByDsCode(dsCode);
        params.put("sql", byDsCode.getSelectClause());
        pageView.setQueryMap(params);
        pageView.setPageNow(pageNow);
        pageView.setPageSize(pageSize);
        try {
            pageView = smDatasourceService.executionSqlPageView(pageView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageView;
    }

    /**
     *
     * 数据源同vform绑定
     * @param dsCode
     * @param selparam
     * @param leftdition
     * @param condition
     * @param dataowner
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "动态执行VFORM中的SQL - 分页处理", notes = "动态执行VFORM中的SQL - 分页处理", httpMethod = "POST")
    @PostMapping(value = "/executinoSqlWithPageTgp")
    public Result executinoSqlWithPageTgp(@RequestParam(value = "dsCode", required = true) String dsCode,
                                            @RequestParam(value = "selparam", required = false) String selparam,
                                            @RequestParam(value = "leftdition", required = false) String leftdition,
                                            @RequestParam(value = "condition", required = false) String condition,
                                            @RequestParam(value = "dataowner", required = false) String dataowner,
                                            @RequestParam(value = "pageNo", required = true) String pageNo,
                                            @RequestParam(value = "pageSize", required = true) String pageSize) {
        Result result = null;
        SmDatasource byDsCode = smDatasourceService.findByDsCode(dsCode);
        String code = byDsCode.getSelectClause().trim();
        try {
            JSONObject json = new JSONObject();
            if(selparam==null) {
                json.put("[SQL1]", "");
            }else {
                json.put("[SQL1]", selparam);
            }
            if(leftdition==null) {
                json.put("[SQL2]", "");
            }else {
                json.put("[SQL2]", leftdition);
            }
            if(condition==null) {
                json.put("[SQL3]", "");
            }else {
                json.put("[SQL3]", condition);
            }
            result = vformInterface.multiForMsQueryBySql(code, json.toJSONString(),pageNo, pageSize, "Y", "Y", dataowner);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
}
